package com.talent.service.auth.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @ClassName：Oauth2ServerConfig
 * @Author: hszhou
 * @Date: 2025/2/7 9:21
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@AllArgsConstructor
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {



    private final PasswordEncoder passwordEncoder;

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    private final RedisConnectionFactory redisConnectionFactory;

    /**
     * 添加第三方的客户端
     * @param clients
     * @throws Exception
     */

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //第三方客户端名称
                .withClient("talent")
                //第三方客户端秘钥
                .secret(passwordEncoder.encode("123456"))
                //第三方客户端的授权范围
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                //token有效期
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(864000);
        super.configure(clients);
    }

    /**
     * 配置验证管理器 UserDetailService
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
        //将token保存到redis中
        //endpoints.tokenStore(redisTokenStore());

        //token 由jwt产生
        endpoints.tokenStore(jwtTokenStore())
                //jwt如何生成
                .tokenEnhancer(jwtAccessTokenConverter());
        super.configure(endpoints);
    }

    private TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * jwt 公钥与私钥
     * keytool -genkeypair -alias talent -keyalg RSA -keypass talent -keystore talent.jks -validity 365 -storepass
     * 解析公钥
     * keytool -list -rfc --keystore talent.jks | openssl x509 -inform pem -pubkey
     * @return
     */

    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //加载私钥
        ClassPathResource classPathResource = new ClassPathResource("talent.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "talent".toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("talent", "talent".toCharArray()));
        return jwtAccessTokenConverter;
    }


    public TokenStore redisTokenStore(){
        return new RedisTokenStore(redisConnectionFactory);
    }
}
